// Author: wsfuyibing <682805@qq.com>
// Date: 2025-06-24

package user_balance

import (
	"context"
	"gitee.com/go-libs/db-xorm/db"
	"server/app/http/models"
	"server/app/kind"
	"server/app/lib/user_balance/operations/load"
	"server/app/lib/user_balance/operations/lock"
	"server/app/lib/user_balance/operations/unlock"
	"sync"
)

var (
	once      = new(sync.Once)
	singleton Manager
)

type (
	// Manager
	// 用户余额管理.
	Manager interface {
		Load(ctx context.Context, sess *db.Session, uid kind.UserId) (model *models.UserStatistic, err error)

		// Lock
		// 冻结部分余额.
		//
		// 入参
		//   - ctx: 为上下文
		//   - sess: 事务连接
		//   - uid: 用户(钓友)ID
		//   - balance: 冻结余额
		//   - bo: 操作类型, 此类型用于控制详情页页面地址.
		//   - params: 操作参数, 用于记录操作详情.
		//
		// 入参
		//   - resource: 流水账的主键ID.
		//   - err: 错误原因.
		Lock(
			ctx context.Context,
			sess *db.Session,
			uid kind.UserId,
			balance kind.Balance,
			bo kind.BalanceOperate,
			link kind.Link,
			params kind.LinkParams,
		) (resource int64, err error)

		// Unlock
		// 解冻余额.
		Unlock(
			ctx context.Context,
			sess *db.Session,
			uid kind.UserId,
			balance kind.Balance,
			bo kind.BalanceOperate,
			link kind.Link,
			params kind.LinkParams,
		) (err error)
	}

	manager struct{}
)

// New
// 管理器实例.
func New() Manager { return singleton }

// +---------------------------------------------------------------------------+
// | Interface methods                                                         |
// +---------------------------------------------------------------------------+

func (o *manager) Load(ctx context.Context, sess *db.Session, uid kind.UserId) (model *models.UserStatistic, err error) {
	return load.New().Run(ctx, sess, uid)
}

func (o *manager) Lock(ctx context.Context, sess *db.Session, uid kind.UserId, balance kind.Balance, bo kind.BalanceOperate, link kind.Link, params kind.LinkParams) (affects int64, err error) {
	return lock.New().Run(ctx, sess, uid, balance, bo, link, params)
}

func (o *manager) Unlock(ctx context.Context, sess *db.Session, uid kind.UserId, balance kind.Balance, bo kind.BalanceOperate, link kind.Link, params kind.LinkParams) (err error) {
	return unlock.New().Run(ctx, sess, uid, balance, bo, link, params)
}

// +---------------------------------------------------------------------------+
// | Initialize singleton instance                                             |
// +---------------------------------------------------------------------------+

func init() {
	once.Do(func() {
		singleton = &manager{}
	})
}
